########
# What does this do?
#######

#
rm(list=ls())


# load libraries
packs = c('lmtest', 'ggplot2', 'hrbrthemes','interplot', 'cregg',
          'tidyverse')

#
source("r/LoadPkg.R")
#
loadPkg(packs)

# read data
load('data/conjoint-nodup.rda')
conjoint_final = conjoint_nodup
rm(conjoint_nodup)


# id-pair
conjoint_final$contestpair = 
  paste(conjoint_final$recordID, conjoint_final$task_num)

covars_fac = c('tierras_fac', 'elections_fac', 'reint_fac', 'just_fac', 
               'repar_fac', 'drugs_fac')

form_fac = formula(paste('chosen_dummy ~ ', paste(covars_fac, collapse = '+')))

# replace with longer name
var_replace = c('no transfer', 'small transfer', 'large transfer', 
                'no electoral par.',
                'FARC competes', 'FARC competes + seats', 
                'no assistance',
                '90% min. wage for demob.', 
                '200% min. wage for demob.', 
                'no jail',
                'jail for HR violators', 
                'jail for all FARC', 
                'no reparations',
                'FARC ask forgiveness', 'FARC pay victims', 
                'aerial fummigation',
                'manual eradication', 'substitution program') %>% 
  Hmisc::capitalize()


# diff in marginal means --------------------------------------------------


# dummy out rearing agg for analysis
conjoint_final$rearing_dum = ifelse(conjoint_final$rearing_agg >= 
                                      median(conjoint_final$rearing_agg), 1, 0)


# get mms
mm = cj(formula = form_fac, id = ~case_id, data = conjoint_final,
        estimate = 'mm_diff', by = ~rearing_dum)

mm %>% 
  as.data.frame %>% 
  mutate(feature = recode(feature,
                          "tierras_fac" = 'Reform - Land', 
                          "elections_fac" = 'Political - Elections', 
                          "reint_fac" = 'Reintegration - Aid', 
                          "just_fac" = "Justice - Retribution",
                          "repar_fac" = 'Justice - Reparations', 
                          "drugs_fac" = 'Reform - Drug Policy')) %>%
  mutate(label = var_replace) %>% 
  mutate(label = factor(label, levels = rev(var_replace))) %>% 
  ggplot(aes(x = label, y = estimate, ymin = lower, ymax = upper, 
             color = feature)) + geom_pointrange() + 
  coord_flip() + 
  geom_hline(yintercept = 0) + 
  theme_ipsum() + 
  scale_color_brewer(palette = 'Dark2') + 
  theme(legend.position = 'top', legend.title = element_blank()) + 
  labs(y = 'Difference in marginal means (MM)\n comparing respondents above and below median rearing scale', 
       x = 'Agreement provisions')

ggsave(here("repFile", "paper", "figures", "auth-inter-mm.pdf"), 
       device = cairo_pdf)
ggsave(here("repFile", "JOP submission", "auth-inter-mm.eps"), 
       device = cairo_ps)
ggsave(here("repFile", "JOP submission", "auth-inter-mm.pdf"), 
       device = cairo_pdf)
